// pages/allShop/submitorder/submitorder.js;
import {commodityDetail,addressSelectByUserId,orderAdd } from '../../../common/api/shop';
import { paymentCreateOrder } from '../../../common/api/my';
import { unix } from 'dayjs';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopList: [],
    shopObj: [],
    address: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let obj = JSON.parse(options.id);
    console.log('val', options,obj)
   
    obj.forEach(e =>{
      this.getShopInfo(e.id,e.num);
    });
    this.data.shopObj = obj;
    this.setData({
      shopObj: obj
    })
    // this.getAddressSelectByUserId();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e){
    let user = wx.getStorageSync('userInfo');
    console.log(e);
    return {
      title: "杆赢天下，求胜未来。一元乐享好球杆，千万球友的选择",
      imageUrl: "../../../images/shareImg.jpg",
       path: "/pages/index/index?id=" + user.id
    }
  },
  async getAddressSelectByUserId(){
    let user = wx.getStorageSync('userInfo');
    let res = await addressSelectByUserId({
      isDefault:  1,
      userId: user.id
    });
    if(res.length){
      this.setData({
        address: res[0]
      })
    }
  },
  // 请求商品信息
  async getShopInfo(e,num){
    let res = await commodityDetail({id: e,orderId: ''});
    res.num = num;
    this.data.shopList.push(res)
    this.setData({
      shopList: this.data.shopList
    })
  },
  go(){
    let vm = this;
    wx.navigateTo({
      url: '/pages/personalCenter/shopSite/shopSite?type=1',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
          // console.log(data,'返回的值')
          vm.setData({
            address : data
          })
        },
      },
    })
  },
  // 数量控制器
  handleChange(e){
    let item = e.currentTarget.dataset.item;
    this.data.shopObj.forEach(data =>{
      console.log(data)
      if(data.id == item.id){
        data.num = e.detail.value
      }
    })

    this.setData({
      shopObj: this.data.shopObj
    })
    //
    // item.num = e.detail.value;
    // e.currentTarget.dataset.item
  },

  async submit() {

    if(!this.data.address.id){
      wx.showToast({
        title: '请您先选择地址',
        icon: 'none'
      });
      setTimeout(() => {
        this.go();
      }, 800);
      return
    };

   let price = this.data.shopList[0].counterPrice * this.data.shopObj[0].num;
   console.log(price, '价格')
    wx.showLoading({
      title: '请稍等正在生成订单中',
      mask: true
    });
    let user = wx.getStorageSync('userInfo');
    let data = {
      addressId: this.data.address.id,
      money: price,
      userId: user.id,
      price: this.data.shopList[0].retailPrice,
      num:  this.data.shopObj[0].num,
      goodsId:  this.data.shopObj[0].id
    };
   
    let res = await paymentCreateOrder(data);
    wx.hideLoading();
    if(res){
      // this.copy(`https://yuleren.cn/api/payment/pay?orderNo=${res}`)
     
      wx.navigateTo({
        url: '/packageA/orderSuccessful/orderSuccessful?orderNo=' + res,
      })
    }else {
      wx.showToast({
        title: '订单编号不存在',
        icon: 'none'
      });
    }
    
  },
  // 添加订单
  async addOrder(){
    if(!this.data.address.id){
      wx.showToast({
        title: '请您先选择地址',
        icon: 'none'
      });
      setTimeout(() => {
        this.go();
      }, 800);
      return
    };
    wx.showLoading({
      title: '换取中'
    });
    let user = wx.getStorageSync('userInfo');
    let data = {
      addressId: this.data.address.id,
      goods: this.data.shopObj,
      userId: user.id
    };
    let res = await orderAdd(data);
    wx.hideLoading();
    wx.showToast({
      title: '换取成功',
    });
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      })
    }, 800);
  }
,
 //  复制链接
 copy(text) {
  wx.showModal({
    title: '复制链接，浏览器打开',
    content: '',
    showCancel: false,
    confirmText: '复制',
    complete: (res) => {
      if (res.confirm) {
        wx.setClipboardData({
          data: text,
          success: () => {
            wx.showToast({
              title: '复制成功',
              icon: 'none'
            })
          }
        })
      }


    }
  })
},
})